package me.chan.oauth.gitee.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;


@RequestMapping("/oauth")
@Controller
public class OAuthController {

    @Autowired
    RestTemplate restTemplate;

    @Value("${clientId:725da84369e47a2b5b1a0d5adc3b7d2177762210e9ac8c2e8a5d8c3074c8e96c}")
    private String client_id;

    @Value("${redirectUri:http://120.78.175.26:9090/oauth/redirect}")
    private String redirect_uri;

    @Value("${client_secret:87bf929112200dbbf7bf7f8bfc35fb684baad5eff78f89c93c32fc41bcac136a}")
    private String client_secret;

    // 本地缓存
    private List<String> accessTokens = new LinkedList<>();

    @GetMapping("/index")
    public String index() {

        return "index";
    }




    @RequestMapping("/redirect")
    public String redirect(@RequestParam(value = "code", required = false) String code,
                           @RequestParam(value = "state", required = false) String state) {

        String uri = "https://gitee.com/oauth/token?grant_type=authorization_code";
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("code", code);
        params.add("client_id", client_id);
        params.add("redirect_uri", redirect_uri);
        params.add("client_secret", client_secret);
        RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(params, HttpMethod.POST, URI.create(uri));
        ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
        if (responseEntity.getStatusCode().value() == 200) {
            String accessToken = responseEntity.getBody();
            System.out.printf("accessToken from Gitee=====> %s \n", accessToken);
            accessTokens.add(accessToken);
            return accessToken;
        }

        throw new RestClientException("cannot get access_token");
    }


    @GetMapping("/email")
    public String getEmail() {
        // 此处假设accessToken不过期，简单处理...
        String accessToken = accessTokens.get(0);
        String uri = UriComponentsBuilder.fromUriString("https://gitee.com/api/v5/emails")
                                        .queryParam("access_token", accessToken)
                                        .toUriString();
        ResponseEntity<String> response = restTemplate.exchange(URI.create(uri), HttpMethod.GET, null, String.class);
        System.out.println("response from email on Gitee====>\n" +  response.getBody());
        return response.getBody();
    }

}
